package com.wxj.book.controller;

import com.wxj.book.common.Const;
import com.wxj.book.common.ServerResponse;
import com.wxj.book.pojo.Book;
import com.wxj.book.pojo.Borrow;
import com.wxj.book.pojo.User;
import com.wxj.book.service.BookService;
import com.wxj.book.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class BorrowController {
    @Autowired
    private BookService bookService;
    @Autowired
    private BorrowService borrowService;

    /**
     * 借阅图书
     */
    @GetMapping("book/borrowBook")
    @ResponseBody
    public ServerResponse borrowBook(@RequestParam("bookId") Integer bookId, HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("借阅失败，请先登录");
        }
        // 先判断图书馆有没有该图书
        Book book = bookService.getByBookId(bookId);
        if (book == null) {
            return ServerResponse.createByErrorMessage("借阅失败，图书编号不存在");
        }
        // 去查询用户有没有订阅过该图书
        Borrow borrow = borrowService.getByBookId(bookId, user.getStuNum());
        if (borrow != null) {
            return ServerResponse.createByErrorMessage("借阅失败，不能重复订阅");
        }
        // 借阅图书上限
        int count = borrowService.getCountByStuNum(user.getStuNum());
        if (count > Const.BORROW_NUM) {
            return ServerResponse.createByErrorMessage("借阅失败，图书借阅数量达到上限");
        }
        // 可以订阅，写入数据库
        int result = borrowService.insert(user, bookId);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("借阅成功");
        }
        return ServerResponse.createByErrorMessage("借阅失败，请重试");
    }

    /**
     * 归还图书
     */
    @GetMapping("borrow/backBook")
    @ResponseBody
    public ServerResponse backBook(@RequestParam("bookId") Integer bookId, HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("归还图书失败，请先登录");
        }
        int result = borrowService.backBook(bookId, user.getStuNum());
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("归还成功");
        }
        return ServerResponse.createByErrorMessage("归还失败");
    }

}
